import 'package:flutter/material.dart';

enum InputType {
  integer,
  double,
  text,
}

class InputDialog extends StatefulWidget {
  final String title;
  final InputType inputType;
  final num? maxValue;
  final String? initialValue;
  final String? hintText;
  final Function(String) onConfirm;
  final Function()? onCancel;

  const InputDialog({
    super.key,
    required this.title,
    required this.inputType,
    this.maxValue,
    this.initialValue,
    this.hintText,
    required this.onConfirm,
    this.onCancel,
  });

  @override
  State<InputDialog> createState() => _InputDialogState();
}

class _InputDialogState extends State<InputDialog> {
  final TextEditingController _controller = TextEditingController();
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    if (widget.initialValue != null) {
      _controller.text = widget.initialValue!;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  bool _validateInput() {
    final value = _controller.text.trim();

    // 检查是否为空
    if (value.isEmpty) {
      setState(() {
        _errorMessage = '请输入内容';
      });
      return false;
    }

    // 验证数字类型
    if (widget.inputType == InputType.integer) {
      final intValue = int.tryParse(value);
      if (intValue == null) {
        setState(() {
          _errorMessage = '请输入有效的整数';
        });
        return false;
      }

      // 检查最大值
      if (widget.maxValue != null && intValue > widget.maxValue!.toInt()) {
        setState(() {
          _errorMessage = '输入值不能超过${widget.maxValue}';
        });
        return false;
      }
    } else if (widget.inputType == InputType.double) {
      final doubleValue = double.tryParse(value);
      if (doubleValue == null) {
        setState(() {
          _errorMessage = '请输入有效的数字';
        });
        return false;
      }

      // 检查最大值
      if (widget.maxValue != null && doubleValue > widget.maxValue!.toDouble()) {
        setState(() {
          _errorMessage = '输入值不能超过${widget.maxValue}';
        });
        return false;
      }
    }

    // 验证通过
    setState(() {
      _errorMessage = null;
    });
    return true;
  }

  void _onConfirmPressed() {
    if (_validateInput()) {
      widget.onConfirm(_controller.text.trim());
      Navigator.of(context).pop();
    }
  }

  void _onCancelPressed() {
    if (widget.onCancel != null) {
      widget.onCancel!();
    }
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            controller: _controller,
            keyboardType: widget.inputType == InputType.integer
                ? TextInputType.number
                : widget.inputType == InputType.double
                ? TextInputType.numberWithOptions(decimal: true)
                : TextInputType.text,
            decoration: InputDecoration(
              hintText: widget.hintText ?? '请输入${_getInputTypeName()}',
              errorText: _errorMessage,
              border: const OutlineInputBorder(),
            ),
            autofocus: true,
            onChanged: (_) {
              // 用户输入时清除错误信息
              if (_errorMessage != null) {
                setState(() {
                  _errorMessage = null;
                });
              }
            },
          ),
          if (widget.maxValue != null)
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  '最大值: ${widget.maxValue}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ),
            ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: _onCancelPressed,
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _onConfirmPressed,
          child: const Text('确认'),
        ),
      ],
    );
  }

  String _getInputTypeName() {
    switch (widget.inputType) {
      case InputType.integer:
        return '整数';
      case InputType.double:
        return '数字';
      case InputType.text:
        return '内容';
    }
  }
}

// 使用示例
// 显示整数输入对话框
void showIntegerInputDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (context) => InputDialog(
      title: '输入数量',
      inputType: InputType.integer,
      maxValue: 100,
      hintText: '请输入1-100之间的数量',
      onConfirm: (value) {
        print('输入的数量: $value');
        // 处理输入的整数
      },
    ),
  );
}

// 显示小数输入对话框
void showDoubleInputDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (context) => InputDialog(
      title: '输入价格',
      inputType: InputType.double,
      maxValue: 999.99,
      initialValue: '99.99',
      onConfirm: (value) {
        print('输入的价格: $value');
        // 处理输入的小数
      },
    ),
  );
}
